function tick() {
	$('#ticker_01 li:first').slideUp(function() {
		$(this).appendTo($('#ticker_01')).slideDown();
	});
	pause = false;

}

function getlevel1(level0) {

	var options = [];

	$.get('InitList', {'action' : 'getLevel1', 'selLevel0' : level0
	}, function(data) {
		$('#level1List').empty();
		// alert("tes"+data.length);
		$.each(data.names, function(index, name) {
					var option = "<option value=\"" + name + "\">" + name
							+ "</option>";
					options.push(option);
				});

		$('select#level1List').append(options.join("")).selectmenu();
	}, 'json');
}

function getLevel2(level0, level1) {
	var options = [];

	$.get('InitList', {'action' : 'getLevel2', 'selLevel0' : level0, 'selLevel1' : level1}, function(data) {
		$('#level2List').empty();
		// alert("tes"+data.length);
		$.each(data.names, function(index, name) {
					var option = "<option value=\"" + name + "\">" + name
							+ "</option>";
					options.push(option);
					// $('#level2List').append(option);

				});
		$('select#level2List').append(options.join("")).selectmenu();
	}, 'json');
}

function getYear() {
	var options = [];

	$.get('InitList', {'action' : 'getYear'}, function(data) {
		$('#yearList').empty();
		// alert("tes"+data.length);
		$.each(data.names, function(index, name) {
					var option = "<option value=\"" + name + "\">" + name
							+ "</option>";
					options.push(option);
					// $('#yearList').append(option);

				});

		$('select#yearList').append(options.join("")).selectmenu();

	}, 'json');
}

function getMonth(selYear) {
	var options = [];
	$.get('InitList', {
		'action' : 'getMonth',
		'selYear' : selYear
	}, function(data) {
		$('#monthList').empty();
		// alert("tes"+data.length);
		$.each(data.names,
				function(index, name) {
					var option = "<option value=\"" + name + "\">" + name
							+ "</option>";
					options.push(option);
					// $('#monthList').append(option);
				});
		$('select#monthList').append(options.join("")).selectmenu();

	}, 'json');
}

function getDay(selYear, selMonth) {
	var options = [];

	$.get('InitList', {
		'action' : 'getDay',
		'selYear' : selYear,
		'selMonth' : selMonth
	}, function(data) {
		$('#dayList').empty();
		// alert("tes"+data.length);
		$.each(data.names,
				function(index, name) {
					var option = "<option value=\"" + name + "\">" + name
							+ "</option>";
					options.push(option);
					// $('#dayList').append(option);

				});
		$('select#dayList').append(options.join("")).selectmenu();

	}, 'json');
}

function getCity(selCountry) {

	var selCountry = $("#countryList option:selected").text();
	var options = [];
	$.get('InitList', {
		'action' : 'getCity',
		'selCountry' : selCountry
	}, function(data) {
		$('#cityList').empty();

		$.each(data.names,
				function(index, name) {
					var option = "<option value=\"" + name + "\">" + name
							+ "</option>";
					options.push(option);

				});
		$('select#cityList').append(options.join("")).selectmenu();
	}, 'json');

}
function getAll(){
	$.get('GetAll',"",function(data){
		// alert(data.series);
		$('.radioSel').removeAttr('checked');
		//$(".downlist option[value='none']").attr("selected", "selected");
		//$('#level0List').val("none");
		
		showHighChart(data.series,data.title,data.subtitle,data.categories);
	},'json');
	
	var obj = {};
	obj.type = "add";
	obj.operator="all:none";
	//obj.val = "none";
	
	$.get('LogServlet',obj,function(data){
		 //alert(JSON.stringify(data));
		 //alert(JSON.stringify(data.series));
		 //alert(JSON.stringify(data.categories));
	//	console.log("test");
		

		if(data!=null){
		
		$('#selectable').empty();
		
		$.each(data.rec, function(index,el) {
  			//<li class="ui-widget-content">Item 1</li>

			var li = "<li class='ui-widget-content'>"+el+"</li>";
			$('#selectable').append(li);
		});
		
			//alert(data.ret);
		}
	
		
	},'json');
	
	
}


function initList() {
    $( "#selectable" ).selectable();

	$("#queryBtn").button();
	$("#groupBtn").button();
	$('#control').hide();
	$('#control').css('background-image', 'url("' + "image/pause.png" + '")');

	$('#level0List').append("<option value=\"none\">none</option>")
			.selectmenu();
	$('#level1List').append("<option value=\"none\">none</option>")
			.selectmenu();
	$("#level1Selected").hide();

	$('#level2List').append("<option value=\"none\">none</option>")
			.selectmenu();
	$("#level2Selected").hide();
	
	$('#countryList').append("<option value=\"none\">none</option>")
			.selectmenu();
	$('#cityList').append("<option value=\"none\">none</option>").selectmenu();
	$("#citySelected").hide();
	
	$('#yearList').append("<option value=\"none\">none</option>").selectmenu();
	$('#monthList').append("<option value=\"none\">none</option>").selectmenu();
	$("#monthSelected").hide();
	$('#dayList').append("<option value=\"none\">none</option>").selectmenu();
	$("#daySelected").hide();
	

	$.get('InitList', {
		'action' : 'getCountry'
	}, function(data) {
		var options = [];
		$('#countryList').empty();
		// alert("tes"+data.length);
		// if(data.length){
		$.each(data.names,function(index, name) {
					var option = "<option value=\"" + name + "\">" + name+ "</option>";
					options.push(option);
					// $('#countryList').append(option);
					// $('select#speedA').selectmenu();
				});
		// }

		$('select#countryList').append(options.join("")).selectmenu();

	}, 'json');

	$.get('InitList', {
		'action' : 'getLevel0'
	}, function(data) {
		var options = [];
		$('#level0List').empty();
		// alert("tes"+data.length);
		$.each(data.names,
				function(index, name) {
					var option = "<option value=\"" + name + "\">" + name
							+ "</option>";
					options.push(option);
					// $('#level0List').append(option);
				});

		$('#level0List').append(options.join("")).selectmenu();

	}, 'json');

	getYear();
	
	getAll();
	// $('#control').text('pause');

}

function drillDown(){
	var obj = {};
	obj.level0 = $("#level0List option:selected").text();
	obj.level1 = $("#level1List option:selected").text();
	obj.level2 = $("#level2List option:selected").text();

	obj.country = $("#countryList option:selected").text();
	obj.city = $("#cityList option:selected").text();

	obj.day = $("#dayList option:selected").text();
	obj.year = $("#yearList option:selected").text();
	obj.month = $("#monthList option:selected").text();
	
	
	obj.level0Sel = $('#level0Selected').is(':checked');
	obj.level1Sel = $('#level1Selected').is(':checked');
	obj.level2Sel = $('#level2Selected').is(':checked');
	
	obj.countrySel = $('#countrySelected').is(':checked');
	obj.citySel = $('#citySelected').is(':checked');
	
	obj.yearSel = $('#yearSelected').is(':checked');
	obj.monthSel = $('#monthSelected').is(':checked');
	obj.daySel =  $('#daySelected').is(':checked');
	
	$.get('GroupTweets',obj,function(data){
		 //alert(JSON.stringify(data));
		 //alert(JSON.stringify(data.series));
		 //alert(JSON.stringify(data.categories));
		  //alert(data.entropy);
		 $('#entropy').text("Entropy: "+data.entropy);
		 $('#entropy').show();
		 showHighChart(data.series,data.title,data.subtitle,data.categories);
		//showHighChart("[{name: \'Year 1800\',data: [107, 31, 635, 203, 2]}, {name: \'Year 1900\',data: [133, 156, 947, 408, 6]}, {name: \'Year 1901\',data: [973, 914, 4054, 732, 34]}] ","test","test","[\'Africa\', \'America\', \'Asia\', \'Europe\', \'Oceania\']");
	},'json');
}

function setConfirmUnload(on) {

	var obj = {};
	 
	
    $(window).load(function () {
    
    	obj.type = "store";
    	
    	$.get('LogServlet',obj,function(data){  
    		
		},'json');
     
    });

	
	
	window.onbeforeunload = function() {
		
		obj.type = "store";
		
		$.get('LogServlet',obj,function(data){
			 //alert(JSON.stringify(data));
			 //alert(JSON.stringify(data.series));
			 //alert(JSON.stringify(data.categories));
			console.log("test");  
			
			
		},'json');

	};

	
	
	
//	$(window).unload( function () {
//		$.get('LogServlet',obj,function(data){
//			 //alert(JSON.stringify(data));
//			 //alert(JSON.stringify(data.series));
//			 //alert(JSON.stringify(data.categories));
//			  alert("test");
//			 //$('#entropy').text("Entropy: "+data.entropy);
//			 //$('#entropy').show();
//			 //showHighChart(data.series,data.title,data.subtitle,data.categories);
//			//showHighChart("[{name: \'Year 1800\',data: [107, 31, 635, 203, 2]}, {name: \'Year 1900\',data: [133, 156, 947, 408, 6]}, {name: \'Year 1901\',data: [973, 914, 4054, 732, 34]}] ","test","test","[\'Africa\', \'America\', \'Asia\', \'Europe\', \'Oceania\']");
//		},'json');
//	} );

}

function getSelected(){
	
	var obj ={};
	obj.level0 = $("#level0List option:selected").text();
	obj.level1 = $("#level1List option:selected").text();
	obj.level2 = $("#level2List option:selected").text();

	obj.country = $("#countryList option:selected").text();
	obj.city = $("#cityList option:selected").text();

	obj.day = $("#dayList option:selected").text();
	obj.year = $("#yearList option:selected").text();
	obj.month = $("#monthList option:selected").text();
	
	
	obj.level0Sel = $('#level0Selected').is(':checked');
	obj.level1Sel = $('#level1Selected').is(':checked');
	obj.level2Sel = $('#level2Selected').is(':checked');
	
	obj.countrySel = $('#countrySelected').is(':checked');
	obj.citySel = $('#citySelected').is(':checked');
	
	obj.yearSel = $('#yearSelected').is(':checked');
	obj.monthSel = $('#monthSelected').is(':checked');
	obj.daySel =  $('#daySelected').is(':checked');
	
	return obj;
}

$(document).ready(
		function() {		
			 
//			$(window).onbeforeunload(function(){
//				alert("test");
//			});
			
			$( ".selectable" ).selectable({
				  selected: function( event, ui ) {
					  //alert("test");
				  }
				 }
			);
			
		  setConfirmUnload(true);
			
			initList();
			$('.ticker1').empty();

			var pause = false;

			var time = 0;
			
			$(".radioSel").change(function(){
				
				var radioSel = $(this).attr('id');
				var obj = {};
				obj.type ="add";
				
				//selItem = getSelected();
					
				obj.operator = "drill:"+radioSel;
				//obj.sel = selItem;
				
				
				
				$.get('LogServlet',obj,function(data){  
					
					
					if(data!=null){
					
					$('#selectable').empty();
					
					$.each(data.rec, function(index,el) {
			  			//<li class="ui-widget-content">Item 1</li>

						var li = "<li class='ui-widget-content'>"+el+"</li>";
						$('#selectable').append(li);
					});
					
						//alert(data.ret);
					}
				},'json');
				
				drillDown();
			});
			
			
			$(".downList").change(function(){
				var obj = {};
				obj.type = "add";
				var parameter = $(this).attr('id');
				//alert(parameter);
				var val = $(this).find('option:selected').text();
				
				if(val=="none"){	
					obj.operator = "roll:"+parameter+":"+val;
				}
				else{
					obj.operator = "slice:"+parameter+":"+val;
				}
				
				//selItem = getSelected();
				//obj.sel = selItem;
				
				
				$.get('LogServlet',obj,function(data){	
					if(data!=null){
						$('#selectable').empty();
						$.each(data.rec, function(index,el) {
				  			//<li class="ui-widget-content">Item 1</li>
						var li = "<li class='ui-widget-content'>"+el+"</li>";
							$('#selectable').append(li);
						});
						//alert(data.ret);
					}
				},'json');
				
				
				drillDown();
			});
			
			$("#countryList").change(function() {
				getCity();
				var country = $("#countryList option:selected").text();
				if(country!="none"){
					$("#countrySelected").hide();
					$("#citySelected").show();

				}
				else{
					$("#countrySelected").show();
					$("#citySelected").hide();
				}
				//drillDown();

			});
			
			$("#cityList").change(function() {
				//getCity();
				var city = $("#cityList option:selected").text();
				if(city!="none"){
					$("#citySelected").hide();

				}
				else{
					$("#citySelected").show();
				}
				
			});

			$('#level0List').change(function() {
				var level0 = $("#level0List option:selected").text();
				getlevel1(level0);
				
				//var level0 = $("#level0List option:selected").text();
				if(level0!="none"){
					$("#level0Selected").hide();
					$("#level1Selected").show();

				}
				else{
					$("#level0Selected").show();
					$("#level1Selected").hide();

				}

			});

			$('#level1List').change(function() {
				var level0 = $("#level0List option:selected").text();
				var level1 = $("#level1List option:selected").text();
				getLevel2(level0, level1);
			
				//var level1 = $("#level1List option:selected").text();
				if(level1!="none"){
					$("#level1Selected").hide();
					$("#level2Selected").show();

				}
				else{
					$("#level1Selected").show();
					$("#level2Selected").hide();

				}
			});

			$('#level2List').change(function() {
				var level2 = $("#level2List option:selected").text();
				if(level2!="none"){
					$("#level2Selected").hide();
				}
				else{
					$("#level2Selected").show();
				}
			});

			$('#yearList').change(function() {
				var year = $("#yearList option:selected").text();
				getMonth(year);
				
				//var year = $("#yearList option:selected").text();
				if(year!="none"){
					$("#yearSelected").hide();
					$("#monthSelected").show();

				}
				else{
					$("#yearSelected").show();
					$("#monthSelected").hide();

				}
				
			});

			$('#monthList').change(function() {
				var year = $("#yearList option:selected").text();
				var month = $("#monthList option:selected").text();
				getDay(year, month);
			
				if(month!="none"){
					$("#monthSelected").hide();
					$("#daySelected").show();

				}
				else{
					$("#monthSelected").show();
					$("#daySelected").hide();

				}
			});

			$('#dayList').change(function() {
				var day = $("#dayList option:selected").text();
				if(day!="none"){
					$("#daySelected").hide();
				}
				else{
					$("#daySelected").show();
				}
			});

			$('#control').click(
					function() {
						if (pause == false) {
							pause = true;

							clearInterval(time);
							time = 0

							// clearInterval(time);
							$(this).css('background-image',
									'url("' + "image/play.png" + '")');
							// $(this).text('start');
						} else if (pause == true) {
							pause = false;
							$(this).css('background-image',
									'url("' + "image/pause.png" + '")');

							if (time == 0) {

								time = setInterval(function() {
									tick()
								}, 4000);
							}

							$('#example_1').show();
							// $(this).text('pause');
						}
					});
			
			$("#groupBtn").click(function(){
				
				getAll();

				var obj = {};
				obj.type = "store";
				$.get('LogServlet',obj,function(data){	
				},'json');
				
				

			});
			$("#queryBtn").click(
					function() {
						// alert("Hello world!");
						/*
						 * var level0 = $("#level0").val(); var level1 =
						 * $("#level1").val(); var level2 = $("#level2").val();
						 * 
						 * var country = $("#country").val(); var city =
						 * $("#city").val();
						 * 
						 * var year = $("#year").val(); var month =
						 * $("#month").val(); var day = $("#day").val();
						 */

						pause = false;

						$('#control').css('background-image',
								'url("' + "image/pause.png" + '")');
						var obj = {};
						obj.level0 = $("#level0List option:selected").text();
						obj.level1 = $("#level1List option:selected").text();
						obj.level2 = $("#level2List option:selected").text();

						obj.country = $("#countryList option:selected").text();
						obj.city = $("#cityList option:selected").text();

						obj.day = $("#dayList option:selected").text();
						obj.year = $("#yearList option:selected").text();
						obj.month = $("#monthList option:selected").text();

						// var dataString =
						// 'level0='+level0+'&level1='+level1+'&level2='+level2+'&country='+country+'&city='+city+'&year='+year+'&month='+month+'&day='+day;

						var icnt = 0;
						
						
						
//						obj.level0Sel = $('#level0Selected').is(':checked');
//						obj.level1Sel = $('#level1Selected').is(':checked');
//						obj.level2Sel = $('#level2Selected').is(':checked');
//						
//						obj.countrySel = $('#countrySelected').is(':checked');
//						obj.citySel = $('#citySelected').is(':checked');
//						
//						obj.yearSel = $('#yearSelected').is(':checked');
//						obj.monthSel = $('#monthSelected').is(':checked');
//						obj.daySel =  $('#daySelected').is(':checked');
//						
						
						
						$.get('GetTweets', obj, function(data) {
							// alert(JSON.stringify(data));
							// $('#example_1').empty();
							$('.ticker1').empty();
							// $('.ticker1').empty();

							// alert(data);
							// $("#tarea").val('');
							// alert(data.tweets.length);
							$('#tcount').text(
									"Tweets matched count is:"
											+ data.tweets.length);
							if (data.tweets.length) {
								
								addTweetsOnMap(data.tweets);
								
								$('#control').show();
								$('.ticker1').empty();
								$.each(data.tweets, function(i, response) {
									var tweet = response.content;
									var $res = $("<li style=\"width:85%;\"/>");
									$res.append(tweet);
									$res.appendTo($('#ticker_01'));

								});

								if (time == 0) {
									time = setInterval(function() {
										tick()
									}, 4000);
								}

							}
						}, 'json');

					});
			google.maps.event.addDomListener(window, 'load', initialize);
		});

function showHighChart(dataSeries,t,subt,cates) {
	chart = new Highcharts.Chart({
        chart: {
            renderTo: 'cube-container',
            type: 'bar'
        },
        title: {
            text: t
        },
        subtitle: {
            text: subt
        },
        xAxis: {
            categories:cates ,
            title: {
                text: null
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: null,
                align: 'high'
            },
            labels: {
                overflow: 'justify'
            }
        },
        tooltip: {
            //formatter: function() {
//                return ''+
//                    this.series.name +': '+ this.y ;
            //}
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -100,
            y: 100,
            floating: true,
            borderWidth: 1,
            backgroundColor: '#FFFFFF',
            shadow: true
        },
        credits: {
            enabled: false
        },
        series:dataSeries
        });
}